#!/usr/bin/env python3
import requests
import json
import time

def test_cache_system():
    """测试缓存系统的基本功能"""
    print("开始测试分布式缓存系统...")
    
    # 测试节点
    nodes = [9527, 9528, 9529]
    
    # 测试数据
    test_data = {
        "user1": {"name": "Alice", "age": 30},
        "user2": {"name": "Bob", "age": 25},
        "config": {"theme": "dark", "language": "zh-CN"}
    }
    
    # 等待服务启动
    print("等待服务启动...")
    time.sleep(3)
    
    # 测试写入
    print("\n=== 测试写入 ===")
    for key, value in test_data.items():
        for port in nodes:
            try:
                response = requests.post(
                    f'http://127.0.0.1:{port}/',
                    json={key: value},
                    headers={'Content-Type': 'application/json'}
                )
                if response.status_code == 200:
                    print(f"✓ 通过端口 {port} 写入 {key} 成功")
                    break
            except Exception as e:
                print(f"✗ 通过端口 {port} 写入失败: {e}")
    
    # 测试读取
    print("\n=== 测试读取 ===")
    for key in test_data.keys():
        for port in nodes:
            try:
                response = requests.get(
                    f'http://127.0.0.1:{port}/{key}',
                    headers={'Content-Type': 'application/json'}
                )
                if response.status_code == 200:
                    data = response.json()
                    print(f"✓ 通过端口 {port} 读取 {key}: {data}")
                    break
                elif response.status_code == 404:
                    print(f"✗ 通过端口 {port} 读取 {key} 失败: 未找到")
            except Exception as e:
                print(f"✗ 通过端口 {port} 读取失败: {e}")
    
    # 测试删除
    print("\n=== 测试删除 ===")
    for key in list(test_data.keys())[:2]:  # 删除前两个
        for port in nodes:
            try:
                response = requests.delete(
                    f'http://127.0.0.1:{port}/{key}',
                    headers={'Content-Type': 'application/json'}
                )
                if response.status_code == 200:
                    data = response.json()
                    print(f"✓ 通过端口 {port} 删除 {key} 成功: 删除了 {data['deleted']} 项")
                    break
            except Exception as e:
                print(f"✗ 通过端口 {port} 删除失败: {e}")
    
    # 验证删除
    print("\n=== 验证删除 ===")
    for key in list(test_data.keys())[:2]:
        for port in nodes:
            try:
                response = requests.get(
                    f'http://127.0.0.1:{port}/{key}',
                    headers={'Content-Type': 'application/json'}
                )
                if response.status_code == 404:
                    print(f"✓ {key} 已成功删除")
                    break
            except Exception as e:
                print(f"✗ 验证删除失败: {e}")
    
    print("\n测试完成！")

if __name__ == '__main__':
    test_cache_system()
